<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #333;
            font-family: Arial, sans-serif;
        }
        #game {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        #gameCanvas {
            border: 2px solid #fff;
            background-color: #000;
        }
        #score {
            color: #fff;
            font-size: 24px;
            margin-top: 20px;
        }
        #startButton {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 5px;
        }
        #startButton:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div id="game">
        <canvas id="gameCanvas" width="600" height="600"></canvas>
        <div id="score">得分: 0</div>
        <button id="startButton">开始游戏</button>
    </div>

<script>
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const scoreElement = document.getElementById('score');
    const startButton = document.getElementById('startButton');

    const BLOCK_SIZE = 20;
    const GRID_WIDTH = canvas.width / BLOCK_SIZE;
    const GRID_HEIGHT = canvas.height / BLOCK_SIZE;

    let snake = [];
    let food = {};
    let direction = 'right';
    let nextDirection = 'right';
    let score = 0;
    let gameOver = false;
    let gameInterval;
    let speed = 150;

    function initGame() {
        // 初始化蛇
        snake = [
            { x: 10, y: 15 },
            { x: 9, y: 15 },
            { x: 8, y: 15 }
        ];
        
        // 初始化食物
        createFood();
        
        // 重置其他游戏状态
        direction = 'right';
        nextDirection = 'right';
        score = 0;
        scoreElement.textContent = `得分: ${score}`;
        gameOver = false;
        
        // 设置游戏循环
        if (gameInterval) clearInterval(gameInterval);
        gameInterval = setInterval(update, speed);
    }

    function createFood() {
        // 生成随机位置的食物，确保不在蛇身上
        let foodPosition;
        do {
            foodPosition = {
                x: Math.floor(Math.random() * GRID_WIDTH),
                y: Math.floor(Math.random() * GRID_HEIGHT)
            };
        } while (snake.some(segment => segment.x === foodPosition.x && segment.y === foodPosition.y));
        
        food = foodPosition;
    }

    function update() {
        if (gameOver) return;
        
        // 更新蛇的移动方向
        direction = nextDirection;
        
        // 获取蛇头位置
        const head = { ...snake[0] };
        
        // 根据方向移动蛇头
        switch (direction) {
            case 'up':
                head.y -= 1;
                break;
            case 'down':
                head.y += 1;
                break;
            case 'left':
                head.x -= 1;
                break;
            case 'right':
                head.x += 1;
                break;
        }
        
        // 检查是否撞墙
        if (head.x < 0 || head.x >= GRID_WIDTH || head.y < 0 || head.y >= GRID_HEIGHT) {
            gameOver = true;
            renderGameOver();
            return;
        }
        
        // 检查是否撞到自己
        if (snake.some(segment => segment.x === head.x && segment.y === head.y)) {
            gameOver = true;
            renderGameOver();
            return;
        }
        
        // 添加新的蛇头
        snake.unshift(head);
        
        // 检查是否吃到食物
        if (head.x === food.x && head.y === food.y) {
            // 吃到食物，加分并创建新食物
            score += 10;
            scoreElement.textContent = `得分: ${score}`;
            createFood();
            
            // 每得100分加快速度
            if (score % 100 === 0) {
                speed = Math.max(50, speed - 10);
                clearInterval(gameInterval);
                gameInterval = setInterval(update, speed);
            }
        } else {
            // 没吃到食物，移除蛇尾
            snake.pop();
        }
        
        // 绘制游戏
        render();
    }

    function render() {
        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 绘制蛇
        snake.forEach((segment, index) => {
            if (index === 0) {
                // 蛇头用不同颜色
                ctx.fillStyle = '#4CAF50';
            } else {
                // 蛇身
                ctx.fillStyle = '#8BC34A';
            }
            ctx.fillRect(segment.x * BLOCK_SIZE, segment.y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
            ctx.strokeStyle = '#000';
            ctx.strokeRect(segment.x * BLOCK_SIZE, segment.y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
        });
        
        // 绘制食物
        ctx.fillStyle = '#FF5722';
        ctx.fillRect(food.x * BLOCK_SIZE, food.y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
        ctx.strokeStyle = '#000';
        ctx.strokeRect(food.x * BLOCK_SIZE, food.y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
    }

    function renderGameOver() {
        ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = 'red';
        ctx.font = '30px Arial';
        ctx.fillText('游戏结束', canvas.width / 2 - 70, canvas.height / 2);
        clearInterval(gameInterval);
    }

    // 键盘控制
    document.addEventListener('keydown', event => {
        if (gameOver) return;

        switch (event.key) {
            case 'ArrowUp':
                // 防止直接反向移动
                if (direction !== 'down') {
                    nextDirection = 'up';
                }
                break;
            case 'ArrowDown':
                if (direction !== 'up') {
                    nextDirection = 'down';
                }
                break;
            case 'ArrowLeft':
                if (direction !== 'right') {
                    nextDirection = 'left';
                }
                break;
            case 'ArrowRight':
                if (direction !== 'left') {
                    nextDirection = 'right';
                }
                break;
        }
    });

    // 开始按钮
    startButton.addEventListener('click', () => {
        initGame();
    });

    // 初始渲染
    render();
</script>
</body>
</html>